package org.sxp.modules.datasource.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.sxp.common.annotation.SysLog;
import org.sxp.common.dto.DatabaseDTO;
import org.sxp.common.dto.TableNamesDTO;
import org.sxp.common.exception.BusinessException;
import org.sxp.common.utils.*;
import org.sxp.common.web.WrapperResponse;
import org.sxp.modules.datasource.dto.PubTableDTO;
import org.sxp.modules.datasource.entity.DatabaseDO;
import org.sxp.modules.datasource.service.DatabaseService;
import org.sxp.modules.sys.controller.AbstractController;

import java.util.*;

/**
 * 
 * @author 沈兴平
 * @date 2021/12/30
 */
@RestController
@RequestMapping(value = "/datasource/pubTable")
@Api(description="Database", tags = "")
@SysLog(modules = "datasource", value = "")
public class PublicTableController extends AbstractController{

    @Autowired
    private DatabaseService databaseService;
    /**
     * 列表
     */
    @ApiImplicitParams({
            @ApiImplicitParam(name="pageNum", value = "当前页码", dataType="int", paramType = "header"),
            @ApiImplicitParam(name="pageSize",value="每页条目",dataType="int", paramType = "header"),
            @ApiImplicitParam(name="orderField",value="排序字段",dataType="string", paramType = "header"),
            @ApiImplicitParam(name="orderType",value="排序类型",dataType="string", paramType = "header", example = "asc或者desc")
    })
    @RequestMapping(value = "/list",method = {RequestMethod.POST})
    @ApiOperation(value = "查询库表列表")
    @RequiresPermissions("datasource:database:list")
    public WrapperResponse<PageResult<TableNamesDTO>> list(DatabaseDTO params) throws Exception{
        DatabaseDO pubDb = databaseService.getOne(
                new LambdaQueryWrapper<DatabaseDO>()
                        .eq(DatabaseDO::getIsPub, true)
                        .eq(DatabaseDO::getId, params.getId())
        );
        if(pubDb == null){
            throw new BusinessException("尚未绑定公共库，请先绑定!!!");
        }
        //请求头获取分页参数
        PageInfo pageInfo = buildPageInfo();
        List<TableNamesDTO> tables = DbUtil.getTableNames(XPBeanUtils.copyBean(pubDb, DatabaseDTO.class));
        return WrapperResponse.success(new PageResult(
                tables.size(),
                Query.countPageNum(tables.size(), pageInfo.getPageSize()),
                pageInfo.getPageSize(),
                pageInfo.getPageNum(), tables));
    }

    /**
     * 绑定公共库
     */
    @RequestMapping(value = "/bindDb", method = {RequestMethod.GET})
    @ApiOperation(value = "绑定公共库")
    public WrapperResponse bindDb(String id) throws Exception{
        DatabaseDO pubDb = databaseService.getOne(new LambdaQueryWrapper<DatabaseDO>()
                .eq(DatabaseDO::getIsPub, true)
        );
        boolean boo = true;
        if(pubDb != null){
            pubDb.setIsPub(false);
            boo = databaseService.updateById(pubDb);
        }

        if(boo){
            DatabaseDO databaseDO = databaseService.getById(id);
            databaseDO.setIsPub(true);
            boo = databaseService.updateById(databaseDO);
        }

        return boo ? WrapperResponse.success(null) : WrapperResponse.fail(null);
    }

    /**
     * 获取公共库
     */
    @RequestMapping(value = "/getPubDb", method = {RequestMethod.GET})
    @ApiOperation(value = "获取公共库")
    public WrapperResponse<DatabaseDO> getPubDb(String dbId) throws Exception{
        DatabaseDO pubDb = databaseService.getOne(new LambdaQueryWrapper<DatabaseDO>()
                .eq(DatabaseDO::getIsPub, true)
                .eq(DatabaseDO::getId, dbId)
        );
        if (pubDb == null) {
            throw new BusinessException("尚未绑定公共库，请先绑定!!!");
        }
        return WrapperResponse.success(pubDb);
    }

}
